<template>
  <div class="sync-control">
    <el-card class="app-card">
      <template #header>
        <div class="card-header">
          <span>同步控制</span>
          <div class="sync-status">
            <el-tag :type="syncing ? 'danger' : 'success'" size="small">
              {{ syncing ? '同步中' : '未同步' }}
            </el-tag>
          </div>
        </div>
      </template>
      
      <div class="sync-content">
        <div class="sync-info mb-20">
          <el-alert
            title="注意事项"
            type="warning"
            description="同步功能需要管理员权限，将把主控窗口的鼠标和键盘操作同步到所有选定的窗口。"
            show-icon
          />
        </div>
        
        <el-form label-position="top">
          <el-form-item label="选择同步窗口">
            <el-table
              v-loading="loading"
              :data="windows"
              @selection-change="handleSelectionChange"
              style="width: 100%"
              height="200"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="number" label="窗口编号" width="100" />
              <el-table-column prop="title" label="窗口标题" min-width="300" />
            </el-table>
          </el-form-item>
          
          <el-form-item label="主控窗口">
            <el-select v-model="masterWindowId" placeholder="请选择主控窗口">
              <el-option 
                v-for="window in selectedWindows" 
                :key="window.id" 
                :label="`${window.number} - ${window.title}`" 
                :value="window.id" 
              />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <div class="sync-settings">
              <el-checkbox v-model="syncOptions.mouseMove">同步鼠标移动</el-checkbox>
              <el-checkbox v-model="syncOptions.mouseClick">同步鼠标点击</el-checkbox>
              <el-checkbox v-model="syncOptions.keyboard">同步键盘输入</el-checkbox>
              <el-checkbox v-model="syncOptions.scroll">同步滚轮操作</el-checkbox>
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button 
              v-if="!syncing"
              type="primary" 
              :disabled="!canStartSync || checkingPermission" 
              :loading="checkingPermission" 
              @click="startSync"
            >
              <el-icon><i-ep-video-camera /></el-icon>
              开始同步
            </el-button>
            <el-button 
              v-else
              type="danger" 
              @click="stopSync"
            >
              <el-icon><i-ep-video-camera-off /></el-icon>
              停止同步
            </el-button>
            
            <el-button 
              v-if="!syncing"
              type="info" 
              @click="checkAdminPermission"
            >
              <el-icon><i-ep-document-checked /></el-icon>
              检查权限
            </el-button>
          </el-form-item>
        </el-form>
        
        <div v-if="hasPermission" class="permission-status">
          <el-icon class="success-icon"><i-ep-circle-check /></el-icon>
          <span>已具备管理员权限</span>
        </div>
        <div v-else-if="permissionChecked" class="permission-status warning">
          <el-icon class="warning-icon"><i-ep-warning /></el-icon>
          <span>缺少管理员权限，同步功能可能无法正常工作</span>
          <el-button type="primary" size="small" @click="restartAsAdmin">以管理员身份重启</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import {
  VideoCamera,
  SwitchButton,
  DocumentChecked,
  CircleCheck,
  Warning
} from '@element-plus/icons-vue'

// 使用别名以避免命名冲突
const iEpVideoCamera = VideoCamera
const iEpVideoCameraOff = SwitchButton // 用SwitchButton替代VideoCameraOff图标
const iEpDocumentChecked = DocumentChecked
const iEpCircleCheck = CircleCheck
const iEpWarning = Warning

interface ChromeWindow {
  id: number
  number: number
  title: string
}

const windows = ref<ChromeWindow[]>([])
const selectedWindows = ref<ChromeWindow[]>([])
const masterWindowId = ref<number>(0)
const loading = ref(false)
const syncing = ref(false)
const checkingPermission = ref(false)
const hasPermission = ref(false)
const permissionChecked = ref(false)

const syncOptions = reactive({
  mouseMove: true,
  mouseClick: true,
  keyboard: true,
  scroll: true
})

// 计算是否可以开始同步
const canStartSync = computed(() => {
  return selectedWindows.value.length > 1 && masterWindowId.value > 0
})

// 导入窗口
const importWindows = async () => {
  loading.value = true
  try {
    const result = await window.electronAPI.getChromeWindows()
    windows.value = result
  } catch (error) {
    console.error('导入窗口失败:', error)
    ElMessage.error('导入窗口失败')
  } finally {
    loading.value = false
  }
}

// 处理选择变化
const handleSelectionChange = (selection: ChromeWindow[]) => {
  selectedWindows.value = selection
  
  // 如果选择了窗口但没有设置主控窗口，则自动设置第一个为���控窗口
  if (selection.length > 0 && (!masterWindowId.value || !selection.find(w => w.id === masterWindowId.value))) {
    masterWindowId.value = selection[0].id
  }
  
  // 如果取消了所有选择，清除主控窗口
  if (selection.length === 0) {
    masterWindowId.value = 0
  }
}

// 检查管理员权限
const checkAdminPermission = async () => {
  checkingPermission.value = true
  try {
    const result = await window.electronAPI.checkAdminPermission()
    hasPermission.value = result
    permissionChecked.value = true
    
    if (result) {
      ElMessage.success('已具备管理员权限')
    } else {
      ElMessage.warning('缺少管理员权限，同步功能可能无法正常工作')
    }
  } catch (error) {
    console.error('检查权限失败:', error)
    ElMessage.error('检查权限失败')
  } finally {
    checkingPermission.value = false
  }
}

// 以管理员身份重启
const restartAsAdmin = async () => {
  try {
    await window.electronAPI.restartAsAdmin()
  } catch (error) {
    console.error('重启失败:', error)
    ElMessage.error('重启失败')
  }
}

// 开始同步
const startSync = async () => {
  if (!canStartSync.value) return
  
  // 如果没有检查过权限，先检查权限
  if (!permissionChecked.value) {
    await checkAdminPermission()
    
    // 如果没有管理员权限，显示警告但允许继续
    if (!hasPermission.value) {
      ElMessage.warning('警告：缺少管理员权限，同步功能可能无法正常工作')
    }
  }
  
  try {
    const windowIds = selectedWindows.value.map(w => w.id)
    const result = await window.electronAPI.startSync(windowIds)
    
    if (result.success) {
      syncing.value = true
      ElMessage.success('开始同步')
    } else {
      ElMessage.error(`启动同步失败: ${result.error}`)
    }
  } catch (error) {
    console.error('启动同步失败:', error)
    ElMessage.error('启动同步失败')
  }
}

// 停止同步
const stopSync = async () => {
  try {
    const result = await window.electronAPI.stopSync()
    
    if (result.success) {
      syncing.value = false
      ElMessage.success('已停止同步')
    }
  } catch (error) {
    console.error('停止同步失败:', error)
    ElMessage.error('停止同步失败')
  }
}

// 监听同步状态变化
let unsubscribeSyncStatus: (() => void) | null = null

onMounted(() => {
  importWindows()
  checkAdminPermission()
  
  // 监听同步状态变化事件
  unsubscribeSyncStatus = window.electronEvents.onSyncStatusChange((status) => {
    syncing.value = status
  })
})

onBeforeUnmount(() => {
  // 取消事件监听
  if (unsubscribeSyncStatus) {
    unsubscribeSyncStatus()
  }
  
  // 如果正在同步，停止同步
  if (syncing.value) {
    stopSync()
  }
})
</script>

<style lang="scss" scoped>
.sync-control {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .sync-content {
    .sync-settings {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
    }
  }
  
  .permission-status {
    margin-top: 20px;
    padding: 10px 15px;
    border-radius: 4px;
    background-color: #f0f9ff;
    border: 1px solid #91d5ff;
    color: #1890ff;
    display: flex;
    align-items: center;
    gap: 8px;
    
    &.warning {
      background-color: #fff7e6;
      border: 1px solid #ffd591;
      color: #fa8c16;
    }
    
    .success-icon {
      color: #52c41a;
    }
    
    .warning-icon {
      color: #fa8c16;
    }
    
    .el-button {
      margin-left: auto;
    }
  }
}
</style>